-- 状态管理器
local StateManager = {
    States = {
        IDLE = "idle",           -- 空闲状态
        IN_COMBAT = "combat",    -- 战斗状态
        IN_MAP = "map",         -- 地图状态
        IN_SHOP = "shop",       -- 商店状态
        IN_INVENTORY = "inventory" -- 背包状态
    },
    LastBossExecution = 0,      -- 最后执行BOSS时间戳
    NextResetTime = 0           -- 下次重置时间
}

-- 当前状态
local currentState = StateManager.States.IDLE

-- 状态切换回调函数表
local stateCallbacks = {}

-- 检查状态是否有效
local function isValidState(state)
    for _, value in pairs(StateManager.States) do
        if value == state then
            return true
        end
    end
    return false
end

-- 设置状态
function StateManager.setState(newState)
    if not isValidState(newState) then
        error("Invalid state: " .. tostring(newState))
    end
    
    local oldState = currentState
    currentState = newState
    
    -- 触发状态切换回调
    if stateCallbacks[newState] then
        for _, callback in ipairs(stateCallbacks[newState]) do
            callback(oldState, newState)
        end
    end
end

-- 获取当前状态
function StateManager.getState()
    return currentState
end

-- 添加状态切换回调
function StateManager.addStateCallback(state, callback)
    if not stateCallbacks[state] then
        stateCallbacks[state] = {}
    end
    table.insert(stateCallbacks[state], callback)
end

-- 移除状态切换回调
function StateManager.removeStateCallback(state, callback)
    if stateCallbacks[state] then
        for i, cb in ipairs(stateCallbacks[state]) do
            if cb == callback then
                table.remove(stateCallbacks[state], i)
                break
            end
        end
    end
end

-- 检查是否在指定状态
function StateManager.isInState(state)
    return currentState == state
end

-- 获取小时状态标识
function StateManager.getHourlyState()
    local currentHour = os.date("%H", os.time())
    return {
        lastExecuted = StateManager.LastBossExecution,
        shouldExecute = os.time() >= StateManager.NextResetTime
    }
end

-- 重置小时状态
function StateManager.resetHourlyState()
    local now = os.time()
    local nextReset = os.time({
        year = tonumber(os.date("%Y", now)) or 0,
        month = tonumber(os.date("%m", now)) or 0,
        day = tonumber(os.date("%d", now)) or 0,
        hour = tonumber(os.date("%H", now)) or 0,
        min = 8,
        sec = 0
    })
    if now > nextReset then
        nextReset = nextReset + 3600  -- 如果当前时间已过8分，设置下一小时
    end
    StateManager.NextResetTime = nextReset
    StateManager.LastBossExecution = 0
end

return StateManager